package cd826dong.cloud.oauth.jwt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

//@Configuration
//用于定义配置类，可替换
//        xml
//        配置文件，被注解的类内部包含有一个或多个被
//@Bean
//注解的方法，这些方法将会被
//        AnnotationConfigApplicationContext
//        或
//        AnnotationConfigWebApplicationContext
//        类进行扫描，并用于构建
//        bean
//        定义，初始化
//        Spring
//        容器。
@Configuration
public class JWTTokenConfig {
    @Autowired
    private Serviceconfig serviceconfig;

    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices(){
        DefaultTokenServices services = new DefaultTokenServices();
        services.setTokenStore(tokenStore());
        services.setSupportRefreshToken(true);
        return services;
    }

    //定义令牌转换器
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //对称加密，并从配置文件中获取密钥
        converter.setSigningKey(serviceconfig.getJwtSignKey());
        return converter;
    }

    //定义jwt令牌增强器，用来对载荷进行自定义扩展
    @Bean
    public TokenEnhancer jwtTokenEnhancer(){
        return new JWTTokenEnhancer();
    }
}
